import 'package:flutter/material.dart';
import 'dart:async';
import '../user_proof.dart';
import '../model/socket_msg.dart';
import './room_bloc.dart';
import '../widget/gradient_btn.dart';
import '../static_var.dart';

class DoudizhuRoomBloc extends RoomBloc {
  List landlordCards = [];
  int magnification = 1;

  StreamController<List> _landlordController;
  StreamController<int> _magnificationController;

  DoudizhuRoomBloc({@required BuildContext roomContext}):super(roomContext: roomContext) {
    this._landlordController = StreamController<List>();
    this._magnificationController = StreamController<int>();
  }

  StreamSink<List> get landlordSink => this._landlordController.sink;
  Stream<List> get landlordStream => this._landlordController.stream;

  StreamSink<int> get magnificationSink => this._magnificationController.sink;
  Stream<int> get magnificationStream => this._magnificationController.stream;

  List getLandlordData() {
    return this.landlordCards;
  }
  int getMagnificationData() {
    return this.magnification;
  }

  void setLandlord(Map tData) {
    this.landlordCards = tData['cards'];
    String landlordId = tData['landlord']['id'];
    if(UserProof.userId == landlordId) {
      mainRoleBloc.setLandlord(true, landlordCards.length);
      mainRoleGetCards(this.landlordCards);
      mainRoleBloc.sortCards();
    }else {
      getOtherRoleBloc(landlordId).setLandlord(true, landlordCards.length);
      otherRoleGetCards(landlordId, List.filled(landlordCards.length, ''));
    }
    this.landlordSink.add(this.landlordCards);
  }

  void setMagnificationData(val) {
    this.magnification = val;
    this.magnificationSink.add(this.magnification);
  }

  @override
  void blocListener(dynamic data) {
    var tData = data['data'];
    ResMsgType msgType = SocketMsg.resMsgTypeFromStr[data['type']];
    switch (msgType) {
      case ResMsgType.landlord:
        this.setLandlord(tData);
        break;
      case ResMsgType.updateMagnification:
        this.setMagnificationData(tData);
        break;
      default: super.blocListener(data);
    }
  }

  void clearLandlord() {
    this.landlordCards = [];
    this.landlordSink.add(this.landlordCards);
  }
  void gameEnd(Map gameEndRes) {
    this.showGameEndRes(gameEndRes);
    
    gameEndRes['players'].forEach((player){
      if(player['id'] != UserProof.userId && null != player['cards'] && List.from(player['cards']).length > 0) {
        getOtherRoleBloc(player['id']).setCards(player['cards'], sort: true);
      }
    });
    
    super.gameEnd(gameEndRes);
  }

  void showGameEndRes(Map gameEndRes) {
    List<Widget> gameEndWidgets = [
      Container(
        alignment: Alignment.center,
        padding: EdgeInsets.only(bottom: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(gameEndRes['is_spring_type']==1?'春天':gameEndRes['is_spring_type']==2?'反春天':'', style: TextStyle(color: StaticVar.blueColor, fontSize: 18)),
            Text(gameEndRes['is_landlord_vec'] ? '地主胜' : '农民胜', style: TextStyle(color: StaticVar.yellowColor, fontSize: 26)),
            Text('x'+gameEndRes['magnification'].toString(), style: TextStyle(color: StaticVar.blueColor, fontSize: 18))
          ],
        ),
      )
    ];
    TextStyle textStyle;
    gameEndRes['players'].forEach((player){
      textStyle = TextStyle(color: player['res'] == 'vec' ? StaticVar.blueColor : Colors.red);
      gameEndWidgets.add(
        Container(
          padding: EdgeInsets.symmetric(vertical: 3),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                width: 108,
                child: LimitedBox(
                  maxWidth: 108,
                  child: Text(player['uname'].toString(), maxLines: 1, overflow: TextOverflow.ellipsis, style: textStyle,),
                ),
              ),
              Text(player['integral'].toString(), style: textStyle),
              Text(player['res'] == 'vec' ? '赢' : '输', style: textStyle)
            ],
          ),
        )
      );
    });
    gameEndWidgets.add(
      Container(
        padding: EdgeInsets.only(top: 6),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            GradientBtn(
              width: 80,
              height: 25,
              colorType: 2,
              child: Text('离开', style: TextStyle(color: Colors.white)),
              pressed: (){
                this.sendOutRoom();
                Navigator.of(roomContext).pop();
                Navigator.of(roomContext).pushReplacementNamed('/lobby');
              },
            ),
            GradientBtn(
              width: 100,
              height: 25,
              child: Text('继续游戏', style: TextStyle(color: Colors.white)),
              pressed: (){
                Navigator.of(roomContext).pop();
                this.goonGame();
                this.magnificationSink.add(1);
              },
            )
          ],
        ),
      )
    );
    showDialog(
      context: roomContext,
      builder: (BuildContext context) {
        return SimpleDialog(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: 15, bottom: 8, left: 16, right: 16),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(5)),
                color: Colors.white,
              ),
              width: 300,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: gameEndWidgets,
              ),
            )
          ],
        );
      }
    );
  }

  void goonGame() {
    this.clearLandlord();
    super.goonGame();
  }

  @override
  void dispose(){
    landlordSink.close();
    _landlordController.close();

    magnificationSink.close();
    _magnificationController.close();
    super.dispose();
  }
}